package com.socialuni.common.user.sdk.manage;

import com.socialuni.common.user.sdk.repository.CommonUserAccountRepository;
import com.socialuni.uniapp.sdk.constant.UniPlatformType;
import com.socialuni.uniapp.sdk.exception.UniSdkException;
import com.socialuni.uniapp.sdk.model.UniUnionIdRO;
import com.socialuni.uniapp.sdk.model.UniProviderLoginQO;
import com.socialuni.common.user.model.DO.CommonUserAccountDO;
import com.socialuni.common.user.model.DO.CommonUserDO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CommonUserAccountDOCreate {
    @Resource
    CommonUserAccountRepository uniUserAccountRepository;

    public CommonUserAccountDO create(CommonUserDO user, UniProviderLoginQO loginQO, UniUnionIdRO uniUnionIdRO) throws UniSdkException {
        CommonUserAccountDO accountDO = new CommonUserAccountDO();
        accountDO.setUserId(user.getId());
        accountDO.setPlatform(loginQO.getPlatform());
        accountDO.setProvider(loginQO.getProvider());
        String openId = uniUnionIdRO.getOpenid();
        if (StringUtils.isEmpty(openId)) {
            throw new UniSdkException("openId为空");
        }
        if (UniPlatformType.mp.equals(loginQO.getPlatform())) {
            //相同都为unionid
            accountDO.setMpOpenId(openId);
            accountDO.setAppOpenId("");
        } else {
            accountDO.setAppOpenId(openId);
            accountDO.setMpOpenId("");
        }
        if (StringUtils.isEmpty(uniUnionIdRO.getUnionid())) {
            accountDO.setUnionId("");
        } else {
            accountDO.setUnionId(uniUnionIdRO.getUnionid());
        }
        accountDO.setToken(uniUnionIdRO.getSession_key());
        uniUserAccountRepository.save(accountDO);
        return accountDO;
    }
}
